# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QHBoxLayout
from qfluentwidgets import TransparentToolButton, FluentIcon as FIF
from qframelesswindow import TitleBarBase
from qframelesswindow.utils import win32_utils


class CustomTitleBar(TitleBarBase):
    def __init__(self, parent):
        super().__init__(parent)
        self.horizontalLayout = QHBoxLayout(self)
        self.topBtn = TransparentToolButton(FIF.PIN, self)

        self.topBtn.setFixedSize(46, 32)

        self.horizontalLayout.setSpacing(0)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setAlignment(Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout.addStretch(1)
        self.horizontalLayout.addWidget(self.topBtn, 0, Qt.AlignmentFlag.AlignRight)
        self.horizontalLayout.addWidget(self.minBtn, 0, Qt.AlignmentFlag.AlignRight)
        self.horizontalLayout.addWidget(self.maxBtn, 0, Qt.AlignmentFlag.AlignRight)
        self.horizontalLayout.addWidget(self.closeBtn, 0, Qt.AlignmentFlag.AlignRight)

        self.topBtn.clicked.connect(self.toggleStayOnTop)

    def toggleStayOnTop(self):
        """ 切换 `置顶` 状态 """
        window = self.window()
        window_handle = window.windowHandle()
        if window_handle.flags() & Qt.WindowType.WindowStaysOnTopHint:
            self.topBtn.setIcon(FIF.PIN)
            window_handle.setFlag(Qt.WindowType.WindowStaysOnTopHint, False)
        else:
            self.topBtn.setIcon(FIF.UNPIN)
            window_handle.setFlag(Qt.WindowType.WindowStaysOnTopHint, True)
        win_id = window.winId()
        window.windowEffect.enableBlurBehindWindow(win_id)
        window.windowEffect.addWindowAnimation(win_id)

        window.windowEffect.setAcrylicEffect(win_id)
        if win32_utils.isGreaterEqualWin11():
            window.windowEffect.addShadowEffect(win_id)
